package me.yangteng.zhihudaily.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.google.gson.Gson;

import me.yangteng.zhihudaily.model.LatestNews;
import me.yangteng.zhihudaily.model.StoriesList;
import me.yangteng.zhihudaily.model.Story;

/**
 * Created by MorenYang on 2017/12/20.
 */

public class LocalStoryLoader {
  private static final String TAG = "LocalStoryLoader";

  private SharedPreferences sharedPreferences;
  private Context context;
  private Gson gson;

  public LocalStoryLoader(Context context) {
    this.context = context;
    this.sharedPreferences = context.getSharedPreferences("storyStorage", Context.MODE_PRIVATE);
    gson = new Gson();
  }

  public boolean has(String storageKey) {
    return sharedPreferences.contains(storageKey);
  }

  public String load(String storageKey) {
    Log.d(TAG, "Load " + storageKey);
    return sharedPreferences.getString(storageKey, null);
  }

  public void save(StoriesList storiesList) {
    Log.d(TAG, "Save " + storiesList.getStorageKey());
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(storiesList.getStorageKey(), gson.toJson(storiesList));
    editor.apply();
  }

  public void save(Story story) {
    Log.d(TAG, "Save " + story.getStorageKey());
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(story.getStorageKey(), gson.toJson(story));
    editor.apply();
  }

  public void save(LatestNews latestNews) {
    Log.d(TAG, "Save " + latestNews.getStorageKey());
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(latestNews.getStorageKey(), gson.toJson(latestNews));
    editor.apply();
  }

  public void clear() {
    Log.d(TAG, "Clear");
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.clear();
    editor.apply();
  }
}
